package com.baixun.gassystem.filter;

import com.baixun.gascommon.ApiDischarged.StaticApi;
import com.baixun.gascommon.ApiDischarged.TokenApi;
import com.baixun.gascommon.utils.R;
import com.baixun.gascommon.utils.ThreadLocalUtils;
import com.baixun.gascommon.utils.TokenUntil;
import com.baixun.gasentity.entity.SysDepartmentUser;
import com.baixun.gassystem.mapper.SysDepartmentUserMapper;
import com.baixun.gassystem.service.AuthorityService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 *    token验证过滤器，不需要自己手动去验证token了，每次请求都会走这里验证携带过来的token是否过期，这就是过滤器的强大之处。
 */
@Component
public class TokenCheckFilter extends OncePerRequestFilter {

    @Autowired
    public TokenUntil tokenUntil;

    @Autowired
    public ObjectMapper objectMapper;

    @Autowired
    public SysDepartmentUserMapper userMapper;

    @Autowired
    private AuthorityService authorityService;



    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HashSet<String> staticApis = StaticApi.getApi();
        HashSet<String> tokenApis = TokenApi.getApi();
        //获取token
        String token = request.getHeader("Authorization");
        String requestURI = request.getRequestURI();
        //登录接口,knife4j文档直接放行
        if (tokenApis.contains(requestURI)){
            filterChain.doFilter(request, response);
            return;
        }
        // 允许访问的静态资源路径
        if ( staticApis.stream().anyMatch(requestURI::startsWith)) {
            filterChain.doFilter(request, response);
            return; // 放行静态资源
        }
//        // 放行 /drone-operations/** 路径
//        if (requestURI.startsWith("/drone-operations/")) {
//            filterChain.doFilter(request, response);
//            return;
//        }
        if (token == null){
            writeJson(response,"token不能为空，请先登录",200);
            return;
        }
        //token不为空，则开始校验
        boolean status = tokenUntil.checkToken(token);
        if (!status){
            writeJson(response,"token已经过期，重新登录",0);
            return;
        }

        // 从 token 获取用户信息 (假设 userInfo 中只包含 userId)
        String userInfo = tokenUntil.getUserInfo(token);
        Long userId;
        try {
            userId = Long.parseLong(userInfo); // 根据返回格式调整解析方式
        } catch (NumberFormatException e) {
            writeJson(response, "无效的用户ID", 0);
            return;
        }
//        if (tokenUntil.checkToken(token)){
//            String userInfo = tokenUntil.getUserInfo(token);
//            SysDepartmentUser sysuser= objectMapper.readValue(userInfo, SysDepartmentUser.class);
//
//            List<SimpleGrantedAuthority> authorities = getAuthoritiesForUser(sysuser);
//
//            UsernamePasswordAuthenticationToken authentication  = new UsernamePasswordAuthenticationToken(sysuser, null, authorities);
//
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//
//            ThreadLocalUtils.setThreadLocal(sysuser.getId());
//
//            filterChain.doFilter(request, response);
//        }else {
//            writeJson(response,"token已经过期，重新登录",0);
//        }
//        //保存用户id
//        String userInfo = tokenUntil.getUserInfo(token);
//        SysUser sysUser = objectMapper.readValue(userInfo, SysUser.class);
//        ThreadLocalUtils.setThreadLocal(sysUser.getId());
//        filterChain.doFilter(request, response);


        // 获取用户信息并解析成 SysDepartmentUser 对象
        // 使用 AuthorityService 获取用户权限
        List<GrantedAuthority> authorities = authorityService.getAuthoritiesByUserId(userId);

        // 将用户 ID 作为身份标识，并设置权限到 Spring Security 上下文
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userId, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 保存用户 ID 到 ThreadLocal，方便后续使用
        ThreadLocalUtils.setThreadLocal(userId);

        // 继续过滤链
        filterChain.doFilter(request, response);
    }

    private List<SimpleGrantedAuthority> getAuthoritiesForUser(SysDepartmentUser sysuser) {
        // 根据用户加载权限并转换为 SimpleGrantedAuthority，确保权限在 Spring Security 中生效
        List<String> permissions = userMapper.findPermissionsByUserId(sysuser.getId());

        // 转换权限列表为 SimpleGrantedAuthority 列表，供 Spring Security 使用
        return permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    //前端页面输出
    public void writeJson(HttpServletResponse response,String msg,Integer code) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        R r = new R();
        r.setMsg(msg);
        r.setCode(code);
        r.setData(null);
        writer.println(objectMapper.writeValueAsString(r));
        writer.flush();
    }





}
